<?php
/**
 * User: 五哥派
 * Date: 2024/7/17
 * Tel(同WX): 17335592719
 */
namespace app\api\controller\v1;

use app\api\controller\ApiBase;
use app\api\model\store\Cart as CartModel;
use app\api\model\store\Goods as GoodsModel;
use app\api\model\store\GoodsSku as GoodsSkuModel;
use app\api\service\store\Cart as CartService;
use app\api\service\user\User as UserService;
class Cart extends ApiBase {

    protected $model;
    protected $mGoodsModel;
    protected $mGoodsSkuModel;

    public function __construct(CartModel $model, GoodsModel $mGoodsModel, GoodsSkuModel $mGoodsSkuModel, CartService $sCartService){

        parent::__construct();
        $this->model = $model;
        $this->mGoodsModel = $mGoodsModel;
        $this->mGoodsSkuModel = $mGoodsSkuModel;

        $this->sCartService = new CartService();
    }

    public function getCount(){
        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        $where['user_id'] = $userId;
        $where['is_new'] = 0;
        $count = $this->model->sum($where);
        return success('查询成功', ['count' => $count]);
    }

    public function getList(){
        $cart_ids = $this->request->param('ids', '');
        $is_new = $this->request->param('is_new') ?: 0;//是否立即购买：0否 1是

        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();

        $list = $this->sCartService->lists($userId, $cart_ids, false, $is_new);
        if (empty($list)) {
            return error('查询失败');
        }
        return success('查询成功', ['list' => $list]);
    }

    //添加到购物车
    public function add(){

        $sku_id = $this->request->param('sku_id') ?: 0;//sku_id
        $num = $this->request->param('num') ?: 0;//num
        $props_text = $this->request->param('props_text') ?: '';//sku_id
        $is_new = $this->request->param('is_new') ?: 0;//sku_id
        if($is_new == 0){
            // 获取当前用户ID
            $userId = UserService::getCurrentLoginUserId();
            //$where[] = ['user_id', '=', $userId];
            //$where[] = ['sku_id', '=', $sku_id];
            $where['user_id'] = $userId;
            $where['sku_id'] = $sku_id;
            $cart =  $this->model->findData($where);
            //dump($this->model->getLastSql());die;
            //if ($cart->isEmpty()) {
            if (!$cart) {
                $goodsSku = $this->mGoodsSkuModel->with(['goods'])->where('id', $sku_id)->find();
                if(!$goodsSku) {
                    return error('失败');
                }
                $data = [
                    'user_id' => $userId,
                    'sku_id' => $sku_id,
                    'goods_id' => $goodsSku['goods']['id'],
                    'name' => $goodsSku['goods']['name'],
                    'image' => $goodsSku['goods']['origin_image'],
                    //'price' => $price,
                    'num' => $num,
                    //'total_price' => $price * $num,
                    'props_text' => $props_text,
                    'is_new' => $is_new,
                    "create_time" => time(),
                    'update_time' => time()
                ];
                $res = $this->model->save($data);
                if(!$res){
                    return error('失败');
                }

            } else {
                $cart->num += $num;
                //$stock = Goods::instance()->getStock($goods_id, $sku_id);
                //if ($cart->num > $stock) {
                //    throw new ValidateException("超出库存数量");
                //}
                $res = $cart->save();
                if(!$res){
                    return error('失败');
                }
            }

            return success('成功');
        }else{
            // 获取当前用户ID
            $userId = UserService::getCurrentLoginUserId();
            $where['user_id'] = $userId;
            $goodsSku = $this->mGoodsSkuModel->with(['goods'])->where('id', $sku_id)->find();
            if(!$goodsSku) {
                return error('失败');
            }
            $data = [
                'user_id' => $userId,
                'sku_id' => $sku_id,
                'goods_id' => $goodsSku['goods']['id'],
                'name' => $goodsSku['goods']['name'],
                'image' => $goodsSku['goods']['origin_image'],
                //'price' => $price,
                'num' => $num,
                //'total_price' => $price * $num,
                'props_text' => $props_text,
                'is_new' => $is_new,
                "create_time" => time(),
                'update_time' => time()
            ];
            $res = $this->model->save($data);
            if(!$res){
                return error('失败');
            }

            return success('成功', ['cartId' => $this->model->id]);
        }

    }


    //更新购物车数量
    public function update(){
        $id = $this->request->param('id');
        $num = $this->request->param('num');

        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();

        //$where[] = ['user_id', '=', $userId];
        //$where[] = ['id', '=', $id];
        $where['user_id'] = $userId;
        $where['id'] = $id;
        //$cart = $this->model->where($where)->findOrEmpty();
        $cart = $this->model->where($where)->find();
        //dump($this->model->getLastSql()); die;
        //if ($cart->isEmpty()) {
        if (!$cart) {
            return error('没有找到商品');
        }
        $cart->num = $num;
        $res = $cart->save();
        if ($res) {
            return success();
        } else {
            return error('减少购物车失败');
        }
    }

    public function delete(){
        $id = $this->request->param('id');
        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        $where['user_id'] = $userId;
        $where['id'] = $id;
        $cart = $this->model->where($where)->find();
        if (!$cart) {
            return error('没有找到商品');
        }
        $cart->delete();
        return success();
    }






}